#include "ObCoin.h"
#include "D3DApp.h"
#include "Collision.h"
#include "ObPlayer.h"

IDirect3DTexture9*	ObCoin::mTex	= 0;
CSound*				ObCoin::sCoin	= 0;

ObCoin::ObCoin(){
	setId(SCORECOIN);
	mInfo	= 0;
}

ObCoin::~ObCoin(){

}

bool ObCoin::setId(int nid){
	if(checkType(nid)){
		mID = nid;
		mWidth	= 16.0f;
		mHeight = 16.0f;
		mCenter = D3DXVECTOR3(mWidth/2, mHeight/2, 0.0f);
		mSpritePos.x = 10;
		mSpritePos.y = 8;
		mCurrentSprite = 0;
		mNeedCollision = true;
		mDelayTime = 0.0f;
		return true;
	}else{
		return false;
	}
}

bool ObCoin::checkType(int obID){
	if(obID==SCORECOIN){
		return true;
	}
	return false;
}

void ObCoin::collidedWith(ObObject* object, CollisionRS rs){
	switch (object->getId())
	{
	case ObPlayer::MARIO:
		PlaySound(sCoin);
		mNeedDispose = true;
		break;
	default:
		break;
	}
}

void ObCoin::update(float dt){
	if(mNeedDispose == false) return;
	mDelayTime+=dt;
	if(mDelayTime>0.1f){
		mDelayTime = 0.0f;
		mCurrentSprite++;
		if(mCurrentSprite > 6){
			mCurrentSprite = 0;
		}
		mSpritePos.x = mCurrentSprite*20 + 10.0f;
	}
}

void ObCoin::render(ID3DXSprite* mSprite){
	if(mID == 0) return;
	if(mTex == 0) return;
	if(mNeedDispose) return;

	HR(gDevice->SetRenderState(D3DRS_ALPHATESTENABLE,true));
	D3DXMATRIX S;
	D3DXMatrixScaling(&S,1.0f,-1.0f,1.0f);
	D3DXMATRIX R;
	D3DXMatrixRotationZ(&R, mRotation);
	D3DXMATRIX T;
	D3DXMatrixTranslation(&T,mPos.x - gCamera->getPos().x,mPos.y - gCamera->getPos().y,0);
	mSprite->SetTransform(&(S*R*T));
	RECT rect = calRenderRECT(mSpritePos,mWidth,mHeight);
	mSprite->Draw(mTex,&rect,&mCenter,0,D3DCOLOR_XRGB(255, 255, 255));
	mSprite->Flush();
	HR(gDevice->SetRenderState(D3DRS_ALPHATESTENABLE,false));
}

bool ObCoin::loadTexture(){
	if(mTex == 0){
		HR(D3DXCreateTextureFromFileEx(
			gDevice,
			"Sprites/Coin.png",
			D3DX_DEFAULT_NONPOW2,
			D3DX_DEFAULT_NONPOW2,
			0,
			0,
			D3DFMT_UNKNOWN,
			D3DPOOL_MANAGED,
			D3DX_DEFAULT,
			D3DX_DEFAULT,
			D3DCOLOR_XRGB(0,0,0),
			NULL,
			NULL,
			&mTex));
		
	}
	sCoin = LoadSound("Sounds\\GetCoin.wav");
	return true;
}
bool ObCoin::releaseTexture(){

	if(sCoin != 0){
		delete sCoin;
	}

	if(mTex!=0){
		ReleaseCOM(mTex);
		return true;
	}else{
		return false;
	}
}